package com.sailing.lianxi.thread;

import java.util.concurrent.Semaphore;

public class SemaphoreTest {

	public static void t1() {
		int N =8;//工人数
		Semaphore semaphore = new Semaphore(4);//机器数
		for(int i=0;i<N;i++) {
			new Worker(i, semaphore).start();
		}
	}
	
	public static void main(String[] args) {
		t1();
	}
}

class Worker extends Thread{
	private int num;
	private Semaphore semaphore;
	public Worker(int num,Semaphore semaphore) {
		 this.num = num;
		 this.semaphore = semaphore;
	}
	
	public void run() {
		try {
			int availablePermits = semaphore.availablePermits();
//			System.out.println("可用的许可数:"+availablePermits);
			semaphore.acquire();
			System.out.println("工人:"+num+" 占用一台机器，在生产");
			Thread.sleep(2000);
			System.out.println("工人:"+num+" 释放出机器");
			semaphore.release();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
